#Boa:Dialog:Dialog1

import wx
import wx.grid

import consultasBD
import utiles
from decimal import Decimal
import sincronizar_tabla

ROJO = (255, 145, 145, 255)
VERDE = (145, 255, 145, 255)
AZUL = (145, 145, 255, 255)
BLANCO = (255, 255, 255, 255)
AMARILLO = (254, 248, 191, 255)
GRIS = ( 220, 220, 220, 255)
NEGRO = ( 0, 0, 0, 255)
VERDENEGRO = ( 47, 79, 79, 255)

def create(parent):
    return Dialog1(parent)

[wxID_DIALOG1, wxID_DIALOG1BUTTON1, wxID_DIALOG1BUTTON2, wxID_DIALOG1BUTTON3, 
 wxID_DIALOG1COMBOBOX1, wxID_DIALOG1COMBOBOX2, wxID_DIALOG1COMBOBOX3, 
 wxID_DIALOG1GRID1, wxID_DIALOG1STATICTEXT1, wxID_DIALOG1STATICTEXT2, 
 wxID_DIALOG1STATICTEXT3, wxID_DIALOG1STATICTEXT4, wxID_DIALOG1STATICTEXT5, 
 wxID_DIALOG1STATICTEXT6, wxID_DIALOG1STATICTEXT7, wxID_DIALOG1STATICTEXT8, 
 wxID_DIALOG1TEXTCTRL1, wxID_DIALOG1TEXTCTRL2, wxID_DIALOG1TEXTCTRL3, 
 wxID_DIALOG1TEXTCTRL4, wxID_DIALOG1TEXTCTRL5, 
] = [wx.NewId() for _init_ctrls in range(21)]

class Dialog1(wx.Dialog):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Dialog.__init__(self, id=wxID_DIALOG1, name='', parent=prnt,
              pos=wx.Point(371, 123), size=wx.Size(498, 381),
              style=wx.DEFAULT_DIALOG_STYLE,
              title='Alta PTC: talle, color, temporada')
        self.SetClientSize(wx.Size(490, 354))

        self.textCtrl1 = wx.TextCtrl(id=wxID_DIALOG1TEXTCTRL1, name='textCtrl1',
              parent=self, pos=wx.Point(16, 24), size=wx.Size(80, 21), style=0,
              value='')
        self.textCtrl1.Bind(wx.EVT_KILL_FOCUS, self.OnKillCodSussan)

        self.textCtrl2 = wx.TextCtrl(id=wxID_DIALOG1TEXTCTRL2, name='textCtrl2',
              parent=self, pos=wx.Point(104, 24), size=wx.Size(272, 21),
              style=0, value='')
        self.textCtrl2.SetEditable(False)

        self.textCtrl3 = wx.TextCtrl(id=wxID_DIALOG1TEXTCTRL3, name='textCtrl3',
              parent=self, pos=wx.Point(104, 64), size=wx.Size(168, 21),
              style=0, value='')
        self.textCtrl3.SetEditable(False)

        self.textCtrl4 = wx.TextCtrl(id=wxID_DIALOG1TEXTCTRL4, name='textCtrl4',
              parent=self, pos=wx.Point(280, 64), size=wx.Size(96, 21), style=0,
              value='')
        self.textCtrl4.SetEditable(False)

        self.comboBox1 = wx.ComboBox(choices=[], id=wxID_DIALOG1COMBOBOX1,
              name='comboBox1', parent=self, pos=wx.Point(384, 112),
              size=wx.Size(60, 21), style=0, value='')
        self.comboBox1.SetLabel('')

        self.comboBox2 = wx.ComboBox(choices=[], id=wxID_DIALOG1COMBOBOX2,
              name='comboBox2', parent=self, pos=wx.Point(384, 152),
              size=wx.Size(100, 21), style=0, value='')
        self.comboBox2.SetLabel('')

        self.comboBox3 = wx.ComboBox(choices=[], id=wxID_DIALOG1COMBOBOX3,
              name='comboBox3', parent=self, pos=wx.Point(384, 192),
              size=wx.Size(100, 21), style=0, value='')
        self.comboBox3.SetLabel('')

        self.button2 = wx.Button(id=wxID_DIALOG1BUTTON2, label='Guardar',
              name='button2', parent=self, pos=wx.Point(408, 288),
              size=wx.Size(75, 23), style=0)
        self.button2.Bind(wx.EVT_BUTTON, self.OnGuardar, id=wxID_DIALOG1BUTTON2)

        self.button1 = wx.Button(id=wxID_DIALOG1BUTTON1, label='Limpiar',
              name='button1', parent=self, pos=wx.Point(16, 320),
              size=wx.Size(75, 23), style=0)
        self.button1.Bind(wx.EVT_BUTTON, self.OnLimpiar, id=wxID_DIALOG1BUTTON1)

        self.button3 = wx.Button(id=wxID_DIALOG1BUTTON3, label='Salir',
              name='button3', parent=self, pos=wx.Point(408, 320),
              size=wx.Size(75, 23), style=0)
        self.button3.Bind(wx.EVT_BUTTON, self.OnSalir, id=wxID_DIALOG1BUTTON3)

        self.staticText1 = wx.StaticText(id=wxID_DIALOG1STATICTEXT1,
              label='Cod Sussan', name='staticText1', parent=self,
              pos=wx.Point(16, 8), size=wx.Size(56, 13), style=0)

        self.staticText2 = wx.StaticText(id=wxID_DIALOG1STATICTEXT2,
              label='Talle', name='staticText2', parent=self, pos=wx.Point(384,
              96), size=wx.Size(22, 13), style=0)

        self.staticText3 = wx.StaticText(id=wxID_DIALOG1STATICTEXT3,
              label='Color', name='staticText3', parent=self, pos=wx.Point(384,
              136), size=wx.Size(25, 13), style=0)

        self.staticText4 = wx.StaticText(id=wxID_DIALOG1STATICTEXT4,
              label='Descripcion', name='staticText4', parent=self,
              pos=wx.Point(104, 8), size=wx.Size(54, 13), style=0)

        self.staticText5 = wx.StaticText(id=wxID_DIALOG1STATICTEXT5,
              label='Proveedor', name='staticText5', parent=self,
              pos=wx.Point(104, 48), size=wx.Size(50, 13), style=0)

        self.staticText6 = wx.StaticText(id=wxID_DIALOG1STATICTEXT6,
              label='Cod.Art.Proveedor', name='staticText6', parent=self,
              pos=wx.Point(280, 48), size=wx.Size(92, 13), style=0)

        self.staticText7 = wx.StaticText(id=wxID_DIALOG1STATICTEXT7,
              label='Temporada', name='staticText7', parent=self,
              pos=wx.Point(384, 176), size=wx.Size(54, 13), style=0)

        self.grid1 = wx.grid.Grid(id=wxID_DIALOG1GRID1, name='grid1',
              parent=self, pos=wx.Point(16, 104), size=wx.Size(360, 208),
              style=0)

        self.staticText8 = wx.StaticText(id=wxID_DIALOG1STATICTEXT8,
              label='Estacion', name='staticText8', parent=self,
              pos=wx.Point(384, 8), size=wx.Size(40, 13), style=0)

        self.textCtrl5 = wx.TextCtrl(id=wxID_DIALOG1TEXTCTRL5, name='textCtrl5',
              parent=self, pos=wx.Point(384, 24), size=wx.Size(100, 21),
              style=0, value='')
        self.textCtrl5.SetEditable(False)

    def __init__(self, parent):
        self._init_ctrls(parent)
        self.crearGrillas()
        self.llenarCombos()
        self.cargaTemporadaCombo()
        self.comboBox1.SetEditable(False)
        self.comboBox2.SetEditable(False)

    def llenarCombos(self):
        sql = "SELECT DISTINCT talle,' ' FROM producto_talle_color WHERE 1 ORDER BY talle"
        talles = consultasBD.ordenCruda(sql)
        for item in talles:
            self.comboBox1.Append(str(item[0]))
        sql = "SELECT idcolor,nombre FROM colores ORDER BY nombre"
        colores = consultasBD.ordenCrudaDict(sql)
        for item in colores:
            color = item["nombre"]+" / "+str(item["idcolor"])
            self.comboBox2.Append(color)

    def cargaTemporadaCombo(self):
        anio = int(utiles.obtenerFecha("Y-m-d")[:4])
        mes = int(utiles.obtenerFecha("Y-m-d")[5:7])
        dia = int(utiles.obtenerFecha("Y-m-d")[-2:])
        anioanterior = anio -1
        anioactual = anio
        aniosiguiente = anio + 1
        self.comboBox3.Append("INVIERNO"+str(anioanterior))
        self.comboBox3.Append("VERANO"+str(anioanterior))
        self.comboBox3.Append("INVIERNO"+str(anioactual))
        self.comboBox3.Append("VERANO"+str(anioactual))
        self.comboBox3.Append("INVIERNO"+str(aniosiguiente))
        self.comboBox3.Append("VERANO"+str(aniosiguiente))
        self.comboBox3.SetEditable(False)

    def ajustarAnchoColumnas(self):
        for y in xrange(self.grid1.GetNumberCols()):
            self.grid1.AutoSizeColumn(y,True)

    def crearGrillas(self):
        #ptc,talle,color,temporada
        #0   1     2     3
        columnas = ['P.T.C','Talle','Color','Temporada']
        self.grid1.CreateGrid(1,len(columnas))
        for i, col in enumerate(columnas): 
            self.grid1.SetColLabelValue(i, col)

        self.ajustarAnchoColumnas()
        self.grid1.EnableEditing(False)
        self.grid1.SetSelectionMode(wx.grid.Grid.wxGridSelectRows)
        self.grid1.Refresh()

    def OnKillCodSussan(self, event):
        codsussan = self.textCtrl1.GetLabel()
        if codsussan == "": return
        self.buscarPTC(codsussan)
        
    def buscarPTC(self,codsussan):
        print "Buscando informacion del producto"
        r1 = "SELECT codartprov FROM producto_codartprov "
        r2 = "WHERE codsussan='"+codsussan+"' "
        sql = r1+r2
        codartprov = consultasBD.ordenCrudaDict(sql)
        try:
            codartproveedor = codartprov[0]["codartprov"]
        except:
            codartproveedor = "-"
        r1 = "SELECT p.descri,pv.idproveedor,pv.nombre, \n"
        r2 = "       p.estacion,p.anio \n"
        r3 = "FROM productos p, proveedor pv \n"
        r4 = "WHERE p.codsussan='"+codsussan+"' AND p.proveedor=pv.idproveedor \n"
        sql = r1+r2+r3+r4
        producto = consultasBD.ordenCrudaDict(sql)
        try:
            descripcion = producto[0]["descri"]
            proveedor = producto[0]["nombre"]+str(producto[0]["idproveedor"])
            estacion = producto[0]["estacion"]+"/"+str(producto[0]["anio"])
        except:
            descripcion = "-"
            proveedor = "-"
            estacion = "-"
        r1 = "SELECT ptc.id AS ptc,ptc.talle,ptc.color,c.nombre AS nombrecolor, \n"
        r2 = "       ptc.temporada \n"
        r3 = "FROM producto_talle_color ptc,colores c \n"
        r4 = "WHERE ptc.codsussan='"+codsussan+"' AND c.idcolor=ptc.color \n"
        r5 = "ORDER BY ptc.id,ptc.talle,c.nombre"
        sql = r1+r2+r3+r4+r5
        ptcs = consultasBD.ordenCrudaDict(sql)
        for fil,item in enumerate(ptcs):
            #ptc,talle,color
            ptc = str(item["ptc"])
            talle = str(item["talle"])
            color = item["nombrecolor"]+" / "+str(item["color"])
            temporada = str(item["temporada"])
            self.grid1.SetCellValue(fil,0,ptc)
            self.grid1.SetCellValue(fil,1,talle)
            self.grid1.SetCellValue(fil,2,color)
            self.grid1.SetCellValue(fil,3,temporada)
            self.grid1.AppendRows()
        self.ajustarAnchoColumnas()
        
        self.textCtrl2.SetLabel(descripcion)
        self.textCtrl3.SetLabel(proveedor)
        self.textCtrl4.SetLabel(codartproveedor)
        self.textCtrl5.SetLabel(estacion)
        self.textCtrl1.SetEditable(False)

    def OnLimpiar(self, event):
        self.grid1.ClearGrid()
        for fil in xrange(self.grid1.GetNumberRows()):
            self.grid1.DeleteRows()
        self.grid1.AppendRows()
        self.textCtrl1.SetLabel("")
        self.textCtrl1.SetEditable(True)
        self.textCtrl2.SetLabel("")
        self.textCtrl3.SetLabel("")
        self.textCtrl4.SetLabel("")
        self.comboBox1.SetSelection(-1)
        self.comboBox2.SetSelection(-1)
        self.comboBox3.SetSelection(-1)
        self.textCtrl1.SetFocus()

    def OnSalir(self, event):
        self.Close()

    def buscar_producto_talle_color(self, codsussan, talle, color, sucursal, temporada):
        '''Retorna el ptc que tenga los atrib de parametro, si no esta lo crea'''
        r1 = "SELECT * FROM producto_talle_color "
        r2 = "WHERE codsussan='%s' AND talle='%s' AND color='%s'" % (codsussan, talle, color)
        sql = r1+r2
        resultados = consultasBD.ordenCrudaResultDictSinCommit(sql)
        if len(resultados) == 0:
            ptc = utiles.secuencia("producto_talle_color", sucursal)
            r1 = "INSERT INTO producto_talle_color ("
            r2 = "id, codsussan, talle, color, temporada) "
            r3 = "VALUES ("
            r4 = "'%s', '%s', '%s', '%s', '%s')" % (ptc, codsussan, talle, color, temporada)
            sql = r1+r2+r3+r4
            sincronizar_tabla.addChange(sql=sql)
            consultasBD.executaSinCommit(None, sql)
            return ptc

    def crear_stock_si_no_esta(self, ptc, sucursal):
        '''Retorna el stock que tenga los atrib de parametro, si no esta lo crea'''
        sql = "SELECT * FROM stock WHERE ptc = '%s' AND sucursal = '%s'" % (ptc, sucursal)
        resultado = consultasBD.ordenCrudaResultDictSinCommit(sql)
        sql_stock = ""
        if len(resultado) == 0:
            print "Creando articulo en stock"
            sql_stock = "INSERT INTO stock (ptc, sucursal, stock) VALUES ('%s', '%s', '%s')" %\
            (ptc, sucursal, "0")
            sincronizar_tabla.addChange(sql=sql_stock)
            consultasBD.executaSinCommit(None, sql_stock)

    def OnGuardar(self, event):
        if self.comboBox1.GetSelection()<0:
            utiles.mensaje(None,"Debe seleccionar TALLE")
            self.comboBox1.SetFocus()
            return
        if self.comboBox2.GetSelection()<0:
            utiles.mensaje(None,"Debe seleccionar COLOR")
            self.comboBox2.SetFocus()
            return
        if self.comboBox3.GetSelection()<0:
            utiles.mensaje(None,"Debe seleccionar TEMPORADA")
            self.comboBox3.SetFocus()
            return
        codsussan = self.textCtrl1.GetLabel()
        talle = self.comboBox1.GetLabel()
        color = self.comboBox2.GetLabel()
        color = (color.split(" / "))[1]
        temporada = self.comboBox3.GetLabel()
        sucursal = utiles.getSucursalActiva()
        for fil in xrange(self.grid1.GetNumberRows()):
            if self.grid1.GetCellValue(fil,0)=="": continue
            t = self.grid1.GetCellValue(fil,1)
            c = self.grid1.GetCellValue(fil,2)
            c = c.split(" / ")[1]
            if talle == t and color == c:
                utiles.mensaje(None,"Ya existe ese Talle y Color")
                return

        try:
            consultasBD.begin()
            print "Creando PTC"
            ptc = self.buscar_producto_talle_color(codsussan,talle,color,sucursal,temporada)
            print "Leyendo sucursales"
            sql = "SELECT idsucursal FROM sucursales ORDER BY idsucursal "
            resultado = consultasBD.ordenCrudaDict(sql)
            sucursales = []
            for item in resultado:
                sucursales.append(str(item["idsucursal"]))
            print "Actualizando stock"
            for sucursal in sucursales:
                self.crear_stock_si_no_esta(ptc,sucursal)
            consultasBD.commit()

        except:
            consultasBD.rollback()
            utiles.mensaje(None,"Error en la grabacion")
            return

        try:
            sincronizar_tabla.syncServerTables(self, ["producto_talle_color", "stock"])
        except:
            utiles.mensaje(None,"Error sincronizando.\nHagalo en forma manual.")
        
        texto = "Para ingresar mercaderia en el Stock\n"
        texto+= "utilice la opcion Ajuste Inventario.\n"
        utiles.mensaje(None,texto)
        
        self.OnLimpiar(None)
        
